<?php

import('@.Service.AppService');
import('@.Service.SubjectService');
import('@.Service.NewsService');
import('@.Service.AppTopService');
import('@.Service.UserService');
import('@.Service.AdService');
import('@.Service.ConfigService');
import('@.Service.SeoService');
import('@.Service.FriendlyLinkService');
import('@.Service.CommentService');
import('@.Util.ConstantUtil');
import('ORG.Util.Image');
import('ORG.Util.String');
import('ORG.Util.Page');
import('@.Filter.BaseAction');
vendor('sinaweibo.saetv2#ex#class');
vendor('simplehtmldom.simple_html_dom');
vendor('tencentweibo.Services.JSON');
vendor('tencentweibo.OpenSDK.Util');
vendor('tencentweibo.OpenSDK.OAuth.Client');
vendor('tencentweibo.OpenSDK.OAuth.Interface');
vendor('tencentweibo.OpenSDK.Tencent.Weibo');

// 本文档自动生成，仅供测试运行
class IndexAction extends BaseAction {

    /**
      +----------------------------------------------------------
     * 默认操作
      +----------------------------------------------------------
     */
    public function index() {
//      dump(load('extend'));return;
        $type = empty($_REQUEST['type']) ? 'iPhone' : $_REQUEST['type'];
        $p = $_REQUEST["p"];



//        $cacheIndexFlag = S(ConstantUtil::$CACHE_INDEX_FLAG . $type . $p);
//        if (!empty($cacheIndexFlag)) {
//            $this->display(APP_PATH . '/Html/Index/index' . $type . $p . '.shtml');
//            return;
//        }


        $appService = new AppService();
//下载排行榜
//热门下载游戏
//$listGamesHot = S(ConstantUtil::$INDEX_HOT_GAMES);
//if (empty($listGamesHot)) {
        $listGamesHot = $appService->listAppHotByTypeName('游戏', 12);
        $this->assign('hotGames', $listGamesHot);
        $listGamesHot1 = $appService->listAppHotByTypeName('游戏', '13,24');
        $this->assign('hotGames1', $listGamesHot1);

//S(ConstantUtil::$INDEX_HOT_GAMES, $listGamesHot, ConstantUtil::$CACHE_TIME);
//}
//热门下载应用
//$listAppsHot = S(ConstantUtil::$INDEX_HOT_APP);
//if (empty($listAppsHot)) {
        $listAppsHot = $appService->listAppHotByTypeName('应用', 12);
        $this->assign('hotApps', $listAppsHot);
        $listAppsHot1 = $appService->listAppHotByTypeName('应用', '13,24');
        $this->assign('hotApps1', $listAppsHot1);
//S(ConstantUtil::$INDEX_HOT_APP, $listAppsHot, ConstantUtil::$CACHE_TIME);
//}
//再次免费
//        $listFreeAgains = S(ConstantUtil::$INDEX_FREE_AGAIN);
//        if (empty($listFreeAgains)) {
//            $listFreeAgains = $appService->listAppFreeAgain();
//            S(ConstantUtil::$INDEX_FREE_AGAIN, $listFreeAgains, ConstantUtil::$CACHE_TIME);
//        }


        $this->assign('listFreeAgains', $listFreeAgains);

//大家都在干什么
        $this->weAreDoing($appService);

//SEO
        $this->seo();
        $this->assign('title', '白泡泡  首页');
//合作伙伴
        $this->setFriendLink(ConstantUtil::$SEO_MODULE[0]);

//两种类型

        $typeService = new TypeService();
        $listTypeApp = S(ConstantUtil::$INDEX_TYPE_APP);
        if (empty($listTypeApp)) {
            $listTypeApp = $typeService->listChildTypesByRootTypeId($typeService->getTypeIdByName('应用'));

            S(ConstantUtil::$INDEX_TYPE_APP, $listTypeApp, ConstantUtil::$CACHE_TIME);
        }

        $listTypeGames = S(ConstantUtil::$INDEX_TYPE_GAMES);
        if (empty($listTypeGames)) {
            $listTypeGames = $typeService->listChildTypesByRootTypeId($typeService->getTypeIdByName('游戏'));

            S(ConstantUtil::$INDEX_TYPE_GAMES, $listTypeGames, ConstantUtil::$CACHE_TIME);
        }

        $this->assign('listTypeApps', $listTypeApp);
        $this->assign('listTypeGames', $listTypeGames);

//Index 广告位
        $ads = F(ConstantUtil::$AD_INDEX);

//首页Logo
//        $indexLogo = F(ConstantUtil::$INDEX_LOGO);
        if (empty($ads)) {
            $adService = new AdService();
            $ads = $adService->listAdByLocation('index');

            F(ConstantUtil::$AD_INDEX, $ads);
        }

//        if (empty($indexLogo)) {
        $adService = new AdService();
        $indexLogo = $adService->findAdByLocation('index_logo');

//            F(ConstantUtil::$INDEX_LOGO, $indexLogo);
//        }
        $this->assign('ads', $ads);

        $this->assign('index_logo', $indexLogo);

        $scroll1 = $adService->findAdByLocation('scroll1');
        $scroll2 = $adService->findAdByLocation('scroll2');
        $scroll3 = $adService->findAdByLocation('scroll3');
        $this->assign('scroll1', $scroll1);
        $this->assign('scroll2', $scroll2);
        $this->assign('scroll3', $scroll3);


//Index News
        $indexNews = S(ConstantUtil::$NEWS_INDEX, ConstantUtil::$CACHE_TIME);
        if (empty($indexNews)) {
            $newsService = new NewsService();
            $news = $newsService->listLatestNews('苹果新闻', 6);
            $price = $newsService->listLatestNews('苹果行情', 3);
            $reviews = $newsService->listLatestNews('苹果评测', 3);

            $indexNews = array('news' => $news, 'price' => $price, 'reviews' => $reviews);
            S(ConstantUtil::$NEWS_INDEX, $indexNews);
        }
        $this->assign('indexNews', $indexNews);

//缓存首页App信息
        $show = S(ConstantUtil::$INDEX_APP_SHOW . $type . $p);
        $list = S(ConstantUtil::$INDEX_APP . $type . $p);
        if (empty($show)) {
            $appService = new AppService();

            $count = $appService->countAppBySmallTypeName($type, $appName);

            $page = new Page($count, 7);

            $map['type'] = $type;
            $map['app_name'] = $appName;
            foreach ($map as $key => $val) {
                $page->parameter .= "$key=" . urlencode($val) . "&";
            }
            $show = $page->show();

            S(ConstantUtil::$INDEX_APP_SHOW . $type . $p, $show, ConstantUtil::$CACHE_TIME);

            $list = $appService->listAppBySmallTypeName($type, $appName, $page->firstRow, $page->listRows, 'datetime desc');

            S(ConstantUtil::$INDEX_APP . $type . $p, $list, ConstantUtil::$CACHE_TIME);
        }


        $this->assign('type', $type);

        $this->assign('list', $list);
        $this->assign('show', $show);

        //标识首页
        $this->assign('index_flag', 'index');

        $this->assign('content', 'Index:index');

//生成静态文件
//设置静态文件时间缓存
        S(ConstantUtil::$CACHE_INDEX_FLAG, ConstantUtil::$CACHE_INDEX_FLAG, ConstantUtil::$CACHE_TIME);
//        echo $this->buildHtml("Index/index" . $type . $p, '', 'Subject:layout_subject');
        $this->display('Subject:layout_subject');
    }

    /**
     * 页面SEO
     */
    function seo($module) {
        if (empty($module)) {
            $module = ConstantUtil::$SEO_MODULE[0];
        }
        $seoService = new SeoService();
        $seo = $seoService->findSeoByModule($module);
        $this->assign('seo_title', $seo['title']);
        $this->assign('seo_content', $seo['description']);
        $this->assign('seo_key', $seo['keyword']);
    }

    function weAreDoing($appService) {
        $listRandTemp = array();
        $listRand = $appService->randApp('id, name, app_icon', 5);
        foreach ($listRand as $rand) {
            $randTemp = $rand;
            $randTemp['datetime'] = '于 ' . date('Y-m-d H:i:s', time() - rand(100, 399)) . ' 被下载';

            array_push($listRandTemp, $randTemp);
        }
        $this->assign('listRand', $listRandTemp);
    }

    /**
     * App 详细信息
     */
    function appInfo() {
        $id = $_REQUEST['id'];

        if (empty($id)) {
            $this->error('您访问的页面不存在');
            return;
        }
        $appService = new AppService();
        $app = $appService->findAppById($id);

        $commentService = new CommentService();
//总评论数
        $commentCount = $commentService->countCommentByAId($app['id']);

        $page = new Page($commentCount, 10);

        $show = $page->show();


        $comments = $commentService->listCommentByAppId($app['id'], $page->firstRow . ',' . $page->listRows);

//        dump(D('comment')->getLastSql());
//        dump($comments);return;
//当前用户是否评过分
        if (Session::is_set(ConstantUtil::$WEB_USER)) {
            $webUser = Session::get(ConstantUtil::$WEB_USER);
            $comm = $commentService->findCommentByUIdAId($webUser['id'], $app['id']);

            $this->assign('comm', $comm);
        }


        $this->assign('commentCount', $commentCount);
        $this->assign('show', $show);
        $this->assign('comments', $comments);
        if (empty($app)) {
            $this->error('您访问的页面不存在');
            return;
        }

        $app['see_num'] += 1;
        $appService->updateApp($app);

//大家都在干什么
        $this->weAreDoing($appService);

//随机用户发布的App
        $uService = new UserService();
        $listUserNickName = $uService->listRandomUser(rand(1, 3));
        $nickName = '';
        foreach ($listUserNickName as $value) {
            $nickName .= $value['nick_name'] . ' ';
        }
        $this->assign('nickName', $nickName);

//下载排行
        $this->appOtherInfo($appService);

//seo 
        $titleName = $app['name'];
        if (strpos($titleName, '：')) {
            $s = split('：', $titleName);
            $titleName = $s[0];

            if (strpos($titleName, '】')) {
                $s = split('】', $titleName);
                $titleName = $s[1];
            }
        }

        $this->assign('seo_title', $titleName . ', 苹果应用' . $app['name'] . '下载 —白泡泡');
        $this->assign('seo_key', $titleName);
        $this->assign('seo_content', '白泡泡24小时更新推荐' . $titleName . '下载');


//合作伙伴
        $this->setFriendLink('首页');

//解开其中的图片路径
        $appImgs = $app['content_img'];
        if (!empty($appImgs)) {
            $imgs = split(';', $appImgs);
            $this->assign('imgs', $imgs);
            $app['content_img'] = $imgs;
        }
//        dump($app);return;
        $this->assign('app', $app);

        $this->assign('content', 'appInfo');
        $this->assign('right', 'right');
        $this->display('Index:global');
    }

//广告位、今日下载排行、本周下载排行
    function appOtherInfo($appService) {
//广告位
        $adByContents = S(ConstantUtil::$AD_CONTENT);
        if (empty($adByContents)) {
            $adService = new AdService();
            $adByContents = $adService->listAdByLocation('content');

            S(ConstantUtil::$AD_CONTENT, $adByContents, ConstantUtil::$CACHE_TIME);
        }
        $this->assign('adContents', $adByContents);

//下载排行
        $weekHotApps = $appService->getAppListByWeekHot();

        $dayHotApps = $appService->getAppListByDayHot();

//内容Logo
        $contentLogo = F(ConstantUtil::$CONTENT_LOGO);
        if (empty($contentLogo)) {
            $adService = new AdService();
            $contentLogo = $adService->findAdByLocation('content_logo');

            F(ConstantUtil::$INDEX_LOGO, $contentLogo);
        }
        $this->assign('contentLogo', $contentLogo);

        $this->assign('weekHotApps', $weekHotApps);
        $this->assign('dayHotApps', $dayHotApps);
    }

    /**
     * 类型列表
     */
    function appTypeList() {
        $type = $this->getType($_REQUEST['type']);
//dump($type);
        if (empty($type)) {
            $type = $_REQUEST['type'];
        }

        if (empty($type)) {
            $this->error('');
            return;
        }
        $appName = $_POST['app_name'];

        $appService = new AppService();
        $count = 0;
        if ('游戏' != $type && '应用' != $type) {
            $count = $appService->countAppBySmallTypeName($type, $appName);
        } else {
            $count = $appService->countAppByTypeName($type, $appName);
        }

        $page = new Page($count, 10);


        $map['type'] = $_REQUEST['type'];
        $map['app_name'] = $appName;
        foreach ($map as $key => $val) {
            $page->parameter .= "$key=" . urlencode($val) . "&";
        }
        $show = $page->show();

        $list = null;
        if ('游戏' != $type && '应用' != $type) {
            $list = $appService->listAppBySmallTypeName($type, $appName, $page->firstRow, $page->listRows, 'datetime desc');
        } else {
            $list = $appService->listAppByTypeName($type, $appName, $page->firstRow, $page->listRows, 'datetime desc');
        }

//大家都在干什么
        $this->weAreDoing($appService);

        $this->appOtherInfo($appService);

//seo 
        $this->assign('seo_title', 'Iphone' . $type . ' 下载，ipad' . $type . ' 下载—白泡泡');
        $this->assign('seo_key', 'Iphone' . $type . ' ipad' . $type . ' ');
        $this->assign('seo_content', '白泡泡24小时更新推荐Iphone' . $type . '下载 Ipad' . $type . '下载');



//合作伙伴
        $this->setFriendLink($type);

        $this->assign('type', $type);

        $this->assign('show', $show);
        $this->assign('list', $list);

        $this->assign('content', 'appTypeList');
        $this->assign('right', 'right');
        $this->display('Index:global');
    }

    /**
     * 中文参数转换
     * @param type $type
     * @return type 
     */
    private function getType($type) {
        if ('limitFree' == $type) {
            return '限时免费';
        } else if ('originalEvaluation' == $type) {
            return '原创评测';
        } else {
            $typeService = new TypeService();
            $type = $typeService->findTypeById($type);

            if (empty($type)) {
                return null;
            }

            return $type['name'];
        }

        return null;
    }

    /**
     * 新闻中心
     */
    function newCenter() {
        $newsService = new NewsService();

        $count = $newsService->countMessages();
        $page = new Page($count, 10);

        $show = $page->show();
        $list = $newsService->listMessages($page->firstRow, $page->listRows, 'datetime desc');
//将Icon转换为内容第一张图片
        //$listT = array();
        foreach ($list as $l) {
            if ('http://icon.cnmo.com/news/more0706/noimg.jpg' == $l['icon']) {
                $contentText = $l['content_text'];

                $html = str_get_html($contentText);
                $imgs = $html->find('img');
                if (0 == count($imgs)) {
                    continue;
                }
                $l['icon'] = array_shift($imgs)->attr['src'];
                $type = Image::getImageInfo($l['icon']);
                $type = $type['type'];
                //dump($type);return;
                $uuid = String::uuid() . '.' . $type;
                $thumbname = './App/Tpl/default/Public/images/upload/' . $uuid;
                Image::thumb($l['icon'], $thumbname, $type, 160, 120);

                $l['icon'] = '../Public/images/upload/' . $uuid;

                $newsService->update($l);
                $html->clear();
            }

            //array_push($listT, $l);
        }
        $list = $newsService->listMessages($page->firstRow, $page->listRows, 'datetime desc');

        $this->assign('type', '新闻');
        $this->assign('show', $show);
        $this->assign('list', $list);
//大家都在干什么
//seo 
        $this->assign('title', '白泡泡  新闻中心');
        $this->seo('新闻');
//合作伙伴
        $this->setFriendLink('新闻');


        $appService = new AppService();
        $this->weAreDoing($appService);
        $this->appOtherInfo($appService);

        $this->assign('content', 'newCenter');
        $this->assign('right', 'right');
        $this->display('Index:global');
    }

    /**
     * 新闻内容
     */
    function newInfo() {
        $id = $_REQUEST['id'];
        if (empty($id)) {
            $this->error('请求页面不存在');
            return;
        }

        $newsService = new NewsService();
        $news = $newsService->findMessageById($id);

        if (empty($news)) {
            $this->error('请求页面不存在');
            return;
        }
        $otherNews = $newsService->listMessagesByOrderMessage($news);

        $fastNavigation = $newsService->fastNavigation($news);


        $this->assign('otherNews', $otherNews);
        $this->assign('fastNavigation', $fastNavigation);
        $navigation = "<a href = '__APP__/Index/newCenter.shtml'> > 新闻中心</a>";

        $this->assign('navigation', $navigation);
        $this->assign('type', '新闻');
        $this->assign('news', $news);

        $appService = new AppService();
        $this->appOtherInfo($appService);
//大家都在干什么
        $this->weAreDoing($appService);


//seo 
        $this->assign('seo_title', $news['name'] . ' —白泡泡');
//合作伙伴
        $this->setFriendLink('新闻');

        $this->assign('content', 'newInfo');
        $this->assign('right', 'right');
        $this->display('Index:global');
    }

    function top() {
        $appTopService = new AppTopService();
        $page = new Page(200, 40);

        $show = $page->show();
        $list = $appTopService->listAppTop($page->firstRow, $page->listRows);

        $this->assign('show', $show);
        $this->assign('list', $list);


        $appService = new AppService();

        $this->assign('allApp', $appService->countAllApp());
        $this->assign('allAppDownLoadNum', $appService->countAllAppDownLoadNum());
        $this->assign('releaseAppByToday', $appService->countReleaseAppByToday());

        $this->assign('type', '排行榜');

//seo 
        $this->assign('title', '白泡泡  排行榜');
        $this->seo('排行榜');
//合作伙伴
        $this->setFriendLink('排行榜');

//top Logo
        $topLogo = F(ConstantUtil::$TOP_LOGO);
        if (empty($topLogo)) {
            $adService = new AdService();
            $topLogo = $adService->findAdByLocation('top');
            F(ConstantUtil::$INDEX_LOGO, $topLogo);
        }
        $this->assign('topLogo', $topLogo);

        $this->assign('content', 'top');
        $this->display('Subject:layout_subject');
    }

    /**
     * 搜索时自动拉取AppName
     */
    function ajaxSearch() {
        $name = $_REQUEST['name'];

        $appService = new AppService();
        $listNames = $appService->listAppByAppName($name, 0, 15, 'download_num desc', 'name');

        $this->ajaxReturn($listNames);
    }

    function search() {
        $name = $_REQUEST['name'];

        $appService = new AppService();
        $count = $appService->countAppByAppName($name);

        $page = new Page($count, 40);

        $map['name'] = $name;
        foreach ($map as $key => $val) {
            $page->parameter .= "$key=" . urlencode($val) . "&";
        }
        $show = $page->show();
        $list = $appService->listAppByAppName($name, $page->firstRow, $page->listRows, 'download_num desc');
        $this->assign('show', $show);
        $this->assign('list', $list);
        $this->assign('count', $count);
        $this->assign('type', '搜索');
        $this->assign('searchName', $name);
        $this->assign('content', 'search');
        $this->display('Subject:layout_subject');
    }

    /**
     * App DownLoad 计数
     */
    function appDownLoad() {
        $id = $_POST['id'];
        if (empty($id)) {
            $this->ajaxReturn('');
            return;
        }
        $appService = new AppService();

        $app = $appService->findAppById($id);
        if (empty($app)) {
            $this->ajaxReturn('');
            return;
        }

        $app['download_num'] += 1;

        $appService->updateApp($app);
    }

    function login() {
//        $validationCode = $_POST['validationCode'];
//        if (empty($validationCode)) {
//            $this->display();
//            return;
//        }
//        if (md5($validationCode) != Session::get('verify')) {
//
//            $this->assign('error', '验证码错误');
//            $this->display();
//            return;
//        }

        $user['email'] = $_POST['email'];
        $user['password'] = md5($_POST['password']);
        $user['enabled'] = 1;
        $user['type'] = 1;

        $userService = new UserService();
        $user = $userService->findUserByLogin($user);

        if (is_null($user)) {
            
        } else {
            SESSION::set(ConstantUtil::$SYSTEM_USER, $user);

            $this->redirect('Admin/index');
        }
    }

    /**
     * 主题
     */
    function subject() {
        $subjectService = new SubjectService();
        $latestSubject = $subjectService->findLatestSubject();

        $count = $subjectService->countSubject($latestSubject['id'], $searchName);

        $page = new Page($count, $limit);
        if (!is_null($searchName)) {
            $map['name'] = $searchName;
            foreach ($map as $key => $val) {
                $page->parameter .= "$key=" . urlencode($val) . "&";
            }
        }
        $show = $page->show();
        $list = $subjectService->listSubject($latestSubject['id'], $page->firstRow . ', ' . $page->listRows, '*', $searchName);

//seo 
        $this->assign('title', '白泡泡  专题');
        $this->seo('专题');
//合作伙伴
        $this->setFriendLink('专题');

        $this->assign('type', '专题');
        $this->assign('latestSubject', $latestSubject);
        $this->assign('list', $list);
        $this->assign('show', $show);

        $this->assign('content', 'Subject:subject');
        $this->display('Subject:layout_subject');
    }

    /**
     * 专题下的集合
     */
    function science() {
        $id = $_REQUEST['id'];
        if (empty($id)) {

            $this->error('');
            return;
        }
        $subjectService = new SubjectService();

//合作伙伴
        $this->setFriendLink('专题');

        $scService = new SubjectContentService();
        $subject = $subjectService->findSubjectById($id);

        $count = $scService->countSubjectContentBySId($id);
        $page = new Page($count, 10);
        $show = $page->show();
        $list = $scService->listSubjectContentBySId($id, $page->firstRow . ', ' . $page->listRows);



        $this->assign('type', '专题');
        $this->assign('subject', $subject);
        $this->assign('otherSubjects', $subjectService->listOtherSubject($subject));
        $this->assign('list', $list);
        $this->assign('show', $show);

//seo 
        $this->assign('seo_title', $subject['name'] . ' , iphone,ipad 应用 ' . $subject['name'] . ' 下载—白泡泡');
        $this->assign('seo_key', $subject['name'] . ' ,iphone,ipad ' . $subject['name']);
        $this->assign('seo_content', '白泡泡24小时不间断, 持久更新推荐iphone,ipad ' . $subject['name'] . '应用下载');

        $this->assign('content', 'Subject:subject_list');
        $this->display('Subject:layout_subject');
    }

    /**
     * Subject Content 详细信息
     */
    function content() {
        $id = $_REQUEST['id'];
        if (empty($id)) {

            $this->error('');
            return;
        }

        $appService = new AppService();
//大家都在干什么
        $this->weAreDoing($appService);

//下载排行
        $this->appOtherInfo($appService);


//合作伙伴
        $this->setFriendLink('专题');


        $scService = new SubjectContentService();
        $sc = $scService->findSubjectById($id);
        $images = split(',', $sc['content_img']);

        $this->assign('images', $images);
        $this->assign('sc', $sc);
        $this->assign('type', '专题');

//seo 
        $this->assign('seo_title', $sc['name'] . ' , iphone,ipad 应用 ' . $sc['name'] . ' 下载—白泡泡');
        $this->assign('seo_key', $sc['name'] . ' ,iphone,ipad ' . $sc['name']);
        $this->assign('seo_content', '白泡泡24小时不间断, 持久更新推荐iphone,ipad ' . $sc['name'] . '应用下载');

        $this->assign('content', 'Subject:subject_content');
        $this->assign('right', 'Index:right');
        $this->display('Index:global');
    }

    /**
     * 登出
     */
    function logout() {
        Session::destroy();

        $this->redirect('/index');
    }

    /**
     * 验证码
     */
    function verify() {
        import("ORG.Util.Image");

        Image::buildImageVerify();
    }

    /**
     * 页脚的友链
     */
    function friendlyLink() {
        $list = F(ConstantUtil::$FRIENDLY_LINK);
        if (empty($list)) {
            $flService = new FriendlyLinkService();
            $list = $flService->listAll();

            F(ConstantUtil::$FRIENDLY_LINK, $list);
        }

        $this->ajaxReturn($list);
    }

    function listWeDoing() {
        $appService = new AppService();

        $data['datetime'] = '于 ' . date('Y-m-d H:i:s', time() - rand(100, 399)) . ' 被下载';
        $data['app'] = $appService->randApp('id, app_icon, name');

        $this->ajaxReturn($data);
    }

    function custom() {
        $id = $_REQUEST['id'];
        if (empty($id)) {

            return;
        }

        $this->display(APP_PATH . '/Html/Custom/' . $id . '.shtml');
    }

//前台用户登陆
    function userLogin() {
        $userService = new UserService();
        $user = $userService->create();

        $loginForwardFlag = 'loginForwardFlag';
        if (empty($user['email']) && empty($user['password'])) {
            if (!Cookie::is_set($loginForwardFlag)) {
//记录登陆前的页面链接
                $httpReferer = $_SERVER ["HTTP_REFERER"];
                Cookie::set($loginForwardFlag, $httpReferer);
            }

            $this->assign('content', 'User:login');
            $this->display('Subject:layout_subject');
            return;
        }
        $user = $userService->validUser($user);

        if (empty($user)) {
            $this->assign('content', 'User:login');
            $this->display('Subject:layout_subject');
            return;
        }
//更新登陆时间
        $user['last_datetime'] = $user['this_datetime'];
        $user['this_datetime'] = ConstantUtil::date();

        $userService->update($user);

        $user['password'] = '';
        SESSION::set(ConstantUtil::$WEB_USER, $user);
        $httpReferer = Cookie::get($loginForwardFlag);
        Cookie::delete($loginForwardFlag);




//页面跳转
        header("location:" . $httpReferer);
    }

//微博登陆，不能登陆进行注册
    function weiboLogin() {
        if ('tencent' == $_REQUEST['weibo']) {
            OpenSDK_Tencent_Weibo::init(ConstantUtil::$WEIBO_TENCENT_APP_KEY, ConstantUtil::$WEIBO_TENCENT_APP_SECRET);
            $token = OpenSDK_Tencent_Weibo::getRequestToken(ConstantUtil::$WEIBO_TENCENT_CALL_BACK_URL);

            header("location:" . OpenSDK_Tencent_Weibo::getAuthorizeURL($token));
            return;
        }
        $o = new SaeTOAuthV2(ConstantUtil::$WEIBO_SINA_APP_KEY, ConstantUtil::$WEIBO_SINA_APP_SECRET);
        $code_url = $o->getAuthorizeURL(ConstantUtil::$WEIBO_SINA_CALL_BACK_URL);
        header("location:" . $code_url);
    }

    //Tencent微博回调接口
    function tencentWeiboCallback() {
        if (isset($_GET['oauth_token']) && isset($_GET['oauth_verifier'])) { //第5，6步
            OpenSDK_Tencent_Weibo::init(ConstantUtil::$WEIBO_TENCENT_APP_KEY, ConstantUtil::$WEIBO_TENCENT_APP_SECRET);
//从Callback返回时
            if (OpenSDK_Tencent_Weibo::getAccessToken($_GET['oauth_verifier'])) {
//此时已经可以正常调用CGI
                $uinfo = OpenSDK_Tencent_Weibo::call('user/info');
                $head = $uinfo['data']['head'];
                $name = $uinfo['data']['name'];

                $user['weibo'] = $name;
                $user['nick_name'] = $name;
                $user['weibo_type'] = 'tencent';
                if (!empty($head)) {
                    $user['avatar'] = $head;
                } else {
                    $user['avatar'] = ConstantUtil::$DEFAULT_HAED_IMG;
                }


                $this->weibo($user);
//                dump($uinfo);
//                echo '从Opent返回并获得授权。你的微博帐号信息为：<br />';
//                echo 'Access token: ', $_SESSION[OpenSDK_Tencent_Weibo::ACCESS_TOKEN], '<br />';
//                echo 'oauth_token_secret: ', $_SESSION[OpenSDK_Tencent_Weibo::OAUTH_TOKEN_SECRET], '<br />';
//                echo '你的微博帐号信息为:<br /><pre>';
//                dump($uinfo);
//echo '<script>closeOpener("'.$uinfo["data"]["name"].'","'.$_SESSION[OpenSDK_Tencent_Weibo::ACCESS_TOKEN].'","'.$_SESSION[OpenSDK_Tencent_Weibo::OAUTH_TOKEN_SECRET].'");</script>';
//echo '<textarea style="width:100%;height:600px;"><script>if(window.showModalDialog){window.returnValue="'.$uinfo["data"]["name"].','.$_SESSION[OpenSDK_Tencent_Weibo::OAUTH_TOKEN].','.$_SESSION[OpenSDK_Tencent_Weibo::OAUTH_TOKEN_SECRET].','.$_SESSION[OpenSDK_Tencent_Weibo::OPENID].','.$_SESSION[OpenSDK_Tencent_Weibo::OPENKEY].'";window.close();}else{closeOpener("'.$uinfo["data"]["name"].'","'.$_SESSION[OpenSDK_Tencent_Weibo::ACCESS_TOKEN].'","'.$_SESSION[OpenSDK_Tencent_Weibo::OAUTH_TOKEN_SECRET].'");}</script></textarea>';
//echo '<script>closeOpener("'.$uinfo["data"]["name"].'","'.$_SESSION[OpenSDK_Tencent_Weibo::ACCESS_TOKEN].'","'.$_SESSION[OpenSDK_Tencent_Weibo::OAUTH_TOKEN_SECRET].'");</script>';
//                echo '<script>closeOpener("' . '' . '","' . '' . '","' . '' . '");</script>';

                header("location:/");
            } else {
                dump($_SESSION);
                echo '获得Access Tokn 失败';
            }
        }
    }

    function sinaWeiboCallback() {
        $o = new SaeTOAuthV2(ConstantUtil::$WEIBO_SINA_APP_KEY, ConstantUtil::$WEIBO_SINA_APP_SECRET);


        if (isset($_REQUEST['code'])) {
            $keys = array();
            $keys['code'] = $_REQUEST['code'];
            $keys['redirect_uri'] = ConstantUtil::$WEIBO_SINA_CALL_BACK_URL;

            try {
                $token = $o->getAccessToken('code', $keys);
                if ($token) {
                    $_SESSION['token'] = $token;
                    setcookie('weibojs_' . $o->client_id, http_build_query($token));
                }

                $url = 'https://api.weibo.com/2/users/show.json?uid=' . $token['uid'] . '&access_token=' . $token['access_token'];

                $content = file_get_contents($url);
                $json = json_decode($content);
                $name = $json->name;


                $user['weibo'] = $name;
                $user['nick_name'] = $name;
                $user['weibo_type'] = 'sina';

                $user['avatar'] = $json->profile_image_url;

                $this->weibo($user);

                header("location:/");
            } catch (OAuthException $e) {
                dump($e);
                $this->error($e);
                return;
            }
        }
    }

    //微博相关注册登陆
    private function weibo($user) {
        $user['enabled'] = 1;
        $user['datetime'] = ConstantUtil::date();

        $uService = new UserService();
        $userT = $uService->findUserByWeibo($user);

        if (empty($userT)) {
            $uService->insertWeibo($user);
            $user['token'] = $token;
            Session::set(ConstantUtil::$WEB_USER, $user);
        } else {
            $userT['token'] = $token;
            Session::set(ConstantUtil::$WEB_USER, $userT);
        }
    }

//微博登出
    function weiboLogout() {
        Session::destroy();

        $this->ajaxReturn(1);
    }

    /**
      +----------------------------------------------------------
     * 探针模式
      +----------------------------------------------------------
     */
    public function checkEnv() {
        load('pointer', THINK_PATH . '/Tpl/Autoindex'); //载入探针函数
        $env_table = check_env(); //根据当前函数获取当前环境
        echo $env_table;
    }

    /**
     * 当前频道的合作伙伴
     * @param type $module 
     */
    private function setFriendLink($module) {
        $friendlyLinkService = new FriendlyLinkService();
        $links = $friendlyLinkService->listAll($module);
        $this->assign('friendlyLinks', $links);
        $this->assign('linkCounts', count($links));
    }

}

?>